<template>
  <div class="account-info">
    <el-form
      ref="formRef"
      :model="form"
      label-width="80px"
      :rules="rules"
      status-icon
    >
      <el-form-item label="原始密码" class="item" prop="oldPwd">
        <el-input v-model="form.oldPwd" />
      </el-form-item>
      <el-form-item label="新密码" class="item" prop="newPwd">
        <el-input type="password" v-model="form.newPwd" />
      </el-form-item>
      <el-form-item label="密码确认" class="item" prop="confirmPwd">
        <el-input type="password" v-model="form.confirmPwd" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">Save</el-button>
        <el-button @click="clearInput">Clear</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import {
  checkUserPassword,
  updateCurrentUserInfo
} from '@/api/personInfoManager.js'

const emits = defineEmits(['initUserInfo'])

const formRef = ref(null)

const form = ref({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})

const checkOldPwd = (rules, value, callback) => {
  if (value === '') {
    return callback(new Error('请输入旧密码'))
  }
  setTimeout(async () => {
    // 向服务器发送请求获取当前用户密码
    try {
      await checkUserPassword({ password: form.value.oldPwd })
      callback()
    } catch (error) {
      callback(new Error(error))
    }
  }, 1000)
}

const validatePass = (rules, value, callback) => {
  if (value === '') {
    return callback(new Error('请输入新密码'))
  } else {
    if (form.value.confirmPwd !== '') {
      formRef.value.validateField('validatePass2')
    }
    callback()
  }
}

const validatePass2 = (rules, value, callback) => {
  if (value === '') {
    callback(new Error('请输入确认密码'))
  } else if (value !== form.value.newPwd) {
    callback(new Error('两次密码输入不匹配,请重新输入'))
  } else {
    callback()
  }
}

const rules = ref({
  oldPwd: [{ validator: checkOldPwd, trigger: 'blur' }],
  newPwd: [{ validator: validatePass, trigger: 'blur' }],
  confirmPwd: [{ validator: validatePass2, trigger: 'blur' }]
})

const clearInput = () => {
  formRef.value.resetFields()
}

const save = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateCurrentUserInfo({ password: form.value.newPwd })
        ElMessage({
          type: 'success',
          duration: 1500,
          message: '更新成功'
        })
        clearInput()

        emits('initUserInfo')
      } catch (error) {
        ElMessage({
          type: 'error',
          duration: 1500,
          message: error
        })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.account-info {
  width: 350px;
  .item {
    margin: 25px 0px;
  }
}
</style>
